# -*- coding: utf_8 -*-
# @Author : RSW
# @Time : 2022/1/8
# @Remark: pyweb
import time
import logging
from typing import NoReturn

from mxsoftpy import DB
from mxsoftpy.exception import DBError, ParamsError

from db.public.IOTManager.iot_base import IOTBaseDB
from index import _
from server.common.IOTManager.AirConditioner.air_conditioner import PrecisionACSelectServer
from server.common.IOTManager.AirConditioner.modbus_ac import ACSelectServer
from server.common.IOTManager.GasDetector.gas_detector import GASDeviceSelectServer
from server.common.IOTManager.Janitor.record import RecordServer
from server.common.IOTManager.PowerCabinet.power_cabinet import PowerDeviceSelectServer
from server.common.IOTManager.TemHumidity.humidity import TemHumidityCheckServer
from server.common.IOTManager.UpsDevice.dev_select import UPSSelectServer
from server.common.IOTManager.Water.water import WaterCheckServer
from server.public.IOTManager.server_base import IOTBaseServer
from utils.classes.custom_exception import VerifyError


def open_database(self, code=0):
    """
    :param self: 类对象
    :param code: 设备项的code --> int
    打开当前数据库当前键的位址
    判断是否数据库存在此键
    """
    try:
        if code:
            return self.tree.open(self.main_key, f"{self.path}\\{code}", file=self.file)
        else:
            return self.tree.open(self.main_key, self.path, file=self.file)
    except DBError as e:
        logging.error(e)
        raise ParamsError('您的操作不被允许')


def is_del(self, code):
    """判断键是否存在"""
    is_parent_dict = open_database(self, code).items(prop_list=['is_del'])
    return is_parent_dict['is_del']


def time_change(stamp):
    """将时间戳转换为格式化时间"""
    time_array = time.localtime(stamp)  # 时间戳转时间数组
    return time.strftime("%Y-%m-%d %H:%M:%S", time_array)  # 时间数组转时间字符串


def get_parent_name(self, parent, p_name):
    """
    :param self:  类对象
    :param parent: 上级机房组
    :param p_name: 基础路径
    :return:
    """
    sub_key = self.tree.open(self.main_key, f'{self.group_path}\\{parent}',
                             file=self.file).items(
        prop_list=['name', 'parent'])
    p_name = '/' + sub_key['name'] + p_name
    if sub_key['parent']:
        p_name = get_parent_name(self, sub_key['parent'], p_name)
    return p_name


class GroupDB(DB):

    def __init__(self):
        """
        self.file : 数据库名
        self.main_key : 主键名
        self.path : 目录
        self.tag : 其他目录
        """
        self.file = 'Co_1'
        self.main_key = 'CRM'
        self.path = 'crm_config\\server_room_group'
        self.sroom_path = "crm_config\\server_room"
        self.group_path = self.path
        # self.tag = 'UNI_Tag'

        super().__init__()

    def all_search(self, search):
        """
        搜索机房与机房组
        :param search: 搜索内容字典
        :return:
        """
        """查询符合记录"""
        tree = open_database(self)
        data_len, data = tree.filter(name__nclike='*' + search + '*')
        data_list = list()  # 递归出本身及下层数据

        def super_level(g_id):
            group_data = tree.sub_items([g_id])
            for key in group_data:
                data_is_del = group_data[key].pop('is_del')
                if data_is_del:
                    continue
                group_data[key]['code'] = key
                if group_data[key]['type'] == 1:
                    group_data[key]['child'] = []
                d_len, d_data = tree.filter(parent=key)
                if d_len:
                    for d_code in d_data:
                        super_level(d_code)
                if group_data[key] not in data_list:
                    data_list.append(group_data[key])

        def parent_level(g_id):
            group_data = tree.sub_items([g_id])
            for key in group_data:
                data_is_del = group_data[key].pop('is_del')
                if data_is_del:
                    continue
                group_data[key]['code'] = key
                if group_data[key]['type'] == 1:
                    group_data[key]['child'] = []

                if search:
                    if group_data[key]['parent']:
                        if group_data[key] not in data_list:
                            data_list.append(group_data[key])
                        parent_level(group_data[key]['parent'])
                    else:
                        if group_data[key] not in data_list:
                            data_list.append(group_data[key])
                if group_data[key] not in data_list:
                    data_list.append(group_data[key])

        """查询记录的上级与下级"""
        for group_id in data:
            """ sub_level 递归下层 """
            if search:
                super_level(group_id)

            """ parent_level 循环上层 """
            parent_level(group_id)

        """添加机房"""
        sroom_list = []
        sroom_len, sroom_key_list = self.tree.open(self.main_key, f"{self.sroom_path}", file=self.file).filter(
            name__nclike='*' + search + '*')
        if sroom_len:
            sroom_key_dict = self.tree.open(self.main_key, f"{self.sroom_path}", file=self.file).sub_items(
                key_list=sroom_key_list)

            for sroom_key, sroom_val in sroom_key_dict.items():
                if sroom_val.pop('is_del'):
                    continue
                sroom_val['code'] = sroom_key
                sroom_val['update_time'] = time_change(sroom_val.pop('update_time'))
                sroom_list.append(sroom_val)
        tree = open_database(self)
        for sroom_i in sroom_list:
            if sroom_i['parent']:
                parent_level(sroom_i['parent'])
        dic = dict()
        for s_key in sroom_list:
            dic[s_key['parent']] = dic.get(s_key['parent'], []) + [s_key]

        """融合上下层"""
        key_list = list()  # 判断是否融合
        for ret_data in data_list:
            for ret_data_1 in data_list:
                if ret_data_1['code'] in key_list:
                    continue
                if ret_data_1['parent'] == ret_data['code']:
                    key_list.append(ret_data_1['code'])
                    ret_data['child'].append(ret_data_1)
                    if dic.get(ret_data_1['code']):
                        for i in dic[ret_data_1['code']]:
                            ret_data_1['child'].append(i)

        """最终返回数据"""
        ret = []
        for i in data_list:
            if not i['parent']:
                ret.append(i)

        for grop_i in ret:
            if dic.get(grop_i['code']):
                for i in dic[grop_i['code']]:
                    grop_i['child'].append(i)

        for sroom_i in sroom_list:
            if not sroom_i['parent']:
                ret.append(sroom_i)

        return _('查询成功'), ret

    def all_list(self):
        """
        展示机房与机房组
        :return:
        """
        """查询所有记录"""
        tree = open_database(self)
        data_list = list()  # 递归出本身及下层数据

        """添加机房组"""

        def add_group(code):
            data_len, data_key_list = tree.filter(parent=code, is_del=0)
            if data_len:
                data_dict = tree.sub_items(key_list=data_key_list)
                sub_list = []
                for data_key, data_val_dict in data_dict.items():
                    data_is_del = data_val_dict.pop('is_del')
                    if data_is_del:
                        continue

                    data_val_dict['code'] = data_key
                    data_val_dict['child'] = []
                    ret_parent_level = add_group(data_key)
                    data_val_dict['child'].extend(ret_parent_level)
                    if not data_val_dict['parent']:
                        data_list.append(data_val_dict)
                    else:
                        sub_list.append(data_val_dict)
                return sub_list
            else:
                return data_key_list

        add_group('')

        """添加机房"""

        def add_sroom(group_list):

            for group_i in group_list:

                if group_i['child']:
                    add_sroom(group_i['child'])
                sroom_len, sroom_key_list = self.tree.open(self.main_key, f"{self.sroom_path}", file=self.file).filter(
                    parent=group_i['code'])
                if sroom_len:
                    sroom_key_dict = self.tree.open(self.main_key, f"{self.sroom_path}", file=self.file).sub_items(
                        key_list=sroom_key_list)
                    for sroom_key, sroom_val in sroom_key_dict.items():
                        if sroom_val.pop('is_del'):
                            continue
                        sroom_val['code'] = sroom_key
                        sroom_val['update_time'] = time_change(sroom_val.pop('update_time'))
                        group_i['child'].append(sroom_val)

        add_sroom(data_list)

        """添加顶层的机房"""
        sroom_top_len, sroom_top_key_list = self.tree.open(self.main_key, f"{self.sroom_path}", file=self.file).filter(
            parent="")
        if sroom_top_len:
            sroom_top_key_dict = self.tree.open(self.main_key, f"{self.sroom_path}", file=self.file).sub_items(
                key_list=sroom_top_key_list)
            for sroom_top_key, sroom_top_val in sroom_top_key_dict.items():
                if sroom_top_val.pop('is_del'):
                    continue
                sroom_top_val['code'] = sroom_top_key
                sroom_top_val['update_time'] = time_change(sroom_top_val.pop('update_time'))
                data_list.append(sroom_top_val)

        return _('查询成功'), data_list

    def list(self, **kwargs):
        """
        显示所有机房组
        :param kwargs:排除显示所选机房组的子类 dict
        :return:
        """
        """查询符合记录"""
        tree = open_database(self)
        group_code = kwargs.get('group_code') if kwargs.get('group_code') else ''
        data_len, data = tree.filter(name__nclike='*')
        data_list = list()  # 递归出本身及下层数据
        if data_len < 1:
            return _('无符合条件的记录'), []

        """整理信息"""

        def parent_level(g_id):
            group_data = tree.sub_items([g_id])
            for key in group_data:
                if key == group_code:
                    continue
                data_is_del = group_data[key].pop('is_del')
                if data_is_del:
                    continue
                group_data[key]['code'] = key
                group_data[key]['child'] = []
                data_list.append(group_data[key])

        for group_id in data:
            parent_level(group_id)

        """形成树状结构"""
        key_list = list()  # 判断是否融合
        for data_i_dict in data_list:
            for data_j_dict in data_list:
                if data_j_dict['code'] in key_list:
                    continue
                if data_j_dict['parent'] == data_i_dict['code']:
                    key_list.append(data_j_dict['code'])
                    data_i_dict['child'].append(data_j_dict)

        """最终返回数据"""
        ret_list = []
        for i in data_list:
            if not i['parent']:
                ret_list.append(i)
        return _('查询成功'), ret_list

    def add(self, **kwargs):
        """
        添加机房组
        :param kwargs:校验后的参数 dict
        :return:
        """

        """判断名称是否存在"""
        data_len, data_code_list = open_database(self).filter(name=kwargs['name'], is_del=0)
        if data_len > 0:
            return _('此机房组名称已存在')

        """添加数据"""
        code_int = open_database(self).insert_key_items(kwargs)
        return _('添加成功'), code_int

    def update(self, code, **kwargs):
        """
        更新机房组
        :param code:机房组的code
        :param kwargs:校验后机房组的参数 dict
        :return:
        """
        """判断机房组是否存在"""
        if int(is_del(self, code)) == 1:
            return _('操作完成'), _('无此机房组')

        """判断名称是否存在"""
        if kwargs.get('name'):
            data_len, data_code_list = open_database(self).filter(name=kwargs['name'], is_del=0)
            if data_len > 0 and data_code_list[0] != code:
                return _('此机房组名称已存在')

        """更新数据"""
        open_database(self, code).insert_items(items=kwargs)

        sroom_list = []

        def get_sub_sroom(group_code):
            d_len, d_code_list = open_database(self).filter(parent=group_code)
            if d_len:
                for i in d_code_list:
                    get_sub_sroom(i)
            s_len, s_code_list = self.tree.open(self.main_key, self.sroom_path, file=self.file).filter(
                parent=group_code)
            sroom_list.extend(s_code_list)

        if kwargs.get('name') or kwargs.get('parent'):
            get_sub_sroom(code)

        for sroom_i in sroom_list:
            """判断是否需要重新生成parent_name"""
            parent_name_route_str = ''
            parent_name_str = '所有机房'

            # def get_parent_name(parent, p_name=parent_name_route_str):
            #     """
            #     :param parent: 上级机房组
            #     :param p_name: 基础路径
            #     :return:
            #     """
            #     sub_key = self.tree.open(self.main_key, f'{self.path}\\{parent}', file=self.file).items(
            #         prop_list=['name', 'parent'])
            #     p_name = '/' + sub_key['name'] + p_name
            #     if sub_key['parent']:
            #         p_name = get_parent_name(sub_key['parent'], p_name)
            #     return p_name
            is_parent_dict = self.tree.open(self.main_key, f"{self.sroom_path}\\{sroom_i}", file=self.file).items(
                prop_list=['parent', 'is_del'])
            if is_parent_dict['is_del']:
                pass
            else:
                parent_name_str += get_parent_name(self, is_parent_dict['parent'], parent_name_route_str)
            self.tree.open(self.main_key, f"{self.sroom_path}\\{sroom_i}", file=self.file).insert_item('parent_name',
                                                                                                       parent_name_str)

        return _('修改成功'), code

    def delete(self, code):
        """
        删除机房组
        :param code: 所选的机房组
        :return:
        """
        """判断机房组是否存在"""
        if int(is_del(self, code)) == 1:
            return _('操作完成'), _('无此机房组')

        open_database(self, code).insert_item('is_del', 1)

        sroom_list = []

        def get_sub_sroom(group_code):
            d_len, d_code_list = open_database(self).filter(parent=group_code)
            if d_len:
                for group_i in d_code_list:
                    open_database(self, group_i).insert_item('is_del', 1)
                    get_sub_sroom(group_i)
            s_len, s_code_list = self.tree.open(self.main_key, self.sroom_path, file=self.file).filter(
                parent=group_code)
            sroom_list.extend(s_code_list)

        get_sub_sroom(code)

        """删除机房"""
        for sroom_i in sroom_list:
            SRoomDB().delete(sroom_i)

        return _('删除成功'), code

    def retrieve(self, code):
        """
        回显机房组
        :param code:所选的机房组
        :return:
        """
        data_dict = open_database(self, code).items()
        if data_dict['is_del']:
            return _('无此机房组')
        data_dict['code'] = code
        data_dict.pop('is_del')
        # data['device'] = 0
        return _('查询成功'), data_dict

    def route(self, code):
        """
        回显机房组路径DB层
        :param code:所选的机房组
        :return:
        """
        ret_list = []

        # data_dict['parent']

        def demo(code_int):
            data_dict = open_database(self, code_int).items()
            if data_dict['parent']:
                demo(data_dict['parent'])
                ret_list.append(data_dict['parent'])

        try:
            demo(code)
            ret_list.append(code)
            return '', ret_list
        except DBError:
            return '此code无效'


class SRoomDB(DB):

    def __init__(self):
        """
        self.file : 数据库名
        self.main_key : 主键名
        self.path : 目录
        self.tag : 其他目录
        """
        self.file = 'Co_1'
        self.main_key = 'CRM'
        self.path = 'crm_config\\server_room'
        self.group_path = 'crm_config\\server_room_group'
        # self.tag = 'UNI_Tag'

        super().__init__()

    def list(self, parent, **search_dict):
        """
        机房详情页(点击组时显示)
        :param parent: 目标机房组
        :param search_dict: 查询参数
        :return:
        """

        """查询包含的机房组"""
        group_list = [parent]

        def get_sub_group(group_code):
            d_len, d_code_list = self.tree.open(self.main_key, self.group_path, file=self.file).filter(
                parent=group_code)
            for group_i in d_code_list:
                is_parent_dict = self.tree.open(self.main_key, f"{self.group_path}\\{group_i}", file=self.file).items(
                    prop_list=['is_del'])
                if is_parent_dict['is_del']:
                    continue
                get_sub_group(group_i)
                group_list.append(group_i)

        get_sub_group(parent)

        """查询包含的机房"""
        sroom_len, sroom_key_dict = open_database(self).filter(parent__in=group_list, is_del=0, **search_dict)

        if not sroom_len:
            return 0, []
        else:
            """整理数据"""
            data_dict = open_database(self).sub_items(key_list=sroom_key_dict)
            ret_list = []
            for data_key, data_val in data_dict.items():
                data_val['code'] = data_key
                data_val.pop('is_del')
                data_val['update_time'] = time_change(data_val.pop('update_time'))
                ret_list.append(data_val)

            return sroom_len, ret_list

    def add(self, **kwargs):
        """
        添加机房
        :param kwargs:校验后的的数据 dict
        :return:
        """
        data_len, data_code_list = open_database(self).filter(name=kwargs['name'], is_del=0)
        if data_len > 0:
            return _('此机房组名称已存在')

        """生成机房到顶级机房组之间的名称"""
        parent_name_str = '所有机房'
        parent_name_route_str = ''
        if kwargs['parent']:
            try:
                parent_name_str += get_parent_name(self, kwargs['parent'], parent_name_route_str)
            except DBError:
                return _('机房的上级有误')
        kwargs["parent_name"] = parent_name_str

        """添加数据"""
        code_int = open_database(self).insert_key_items(kwargs)

        return _('创建成功'), code_int

    def update(self, code, **kwargs):
        """
        更新机房
        :param code: 需要更新 str
        :param kwargs: 更新的数据 dict
        :return:
        """
        """判断机房是否存在"""
        if int(is_del(self, code)) == 1:
            return _('操作完成'), _('无此机房')

        """判断名称是否存在"""
        if kwargs.get('name'):
            data_len, data_code_list = open_database(self).filter(name=kwargs['name'], is_del=0)
            if data_len > 0 and data_code_list[0] != code:
                return _('此机房组名称已存在')

        """判断是否需要重新生成parent_name"""
        parent_name_route_str = ''

        if kwargs['parent']:
            is_parent_dict = open_database(self, code).items(prop_list=['parent'])
            if is_parent_dict['parent'] == kwargs['parent']:
                pass
            else:
                parent_name_str = '所有机房'

                try:
                    parent_name_str += get_parent_name(self, kwargs['parent'], parent_name_route_str)
                    kwargs["parent_name"] = parent_name_str
                except DBError:
                    return _('机房的上级有误')

        """更新数据"""
        open_database(self, code).insert_items(items=kwargs)

        return _('修改成功'), code

    def delete(self, code):
        """
        删除机房
        :param code: 删除所选机房的code
        :return:
        """
        """判断机房是否存在"""
        if int(is_del(self, code)) == 1:
            return _('操作完成'), _('无此机房')

        open_database(self, code).insert_item('is_del', 1)
        vo_len, vo_key_list = self.tree.open(self.main_key, f"{'cabine_manage'}", file=self.file).filter(parent=code)

        """逻辑删除机柜"""
        for vo_i in vo_key_list:
            self.tree.open(self.main_key, f"{'cabine_manage'}\\{vo_i}", file=self.file).insert_item('is_del', 1)

        # todo 删除机房时把动环移除

        return _('删除成功'), code

    def retrieve(self, code):
        """
        回显机房
        :param code: 所选机房的code
        :return:
        """
        data_dict = open_database(self, code).items()
        # if data_dict.get('is_del', 1):
        #     raise ParamsError(_('无此机房'))
        data_dict['code'] = code
        data_dict.pop('is_del')
        data_dict['update_time'] = time_change(data_dict.pop('update_time'))
        # data['device'] = 0
        return _('查询成功'), data_dict

    def route(self, code):
        """
        回显机房路径DB层
        :param code:所选的机房组
        :return:
        """
        ret_list = []
        d_dict = open_database(self, code).items()
        if d_dict['parent']:

            def demo(code_int):
                data_dict = self.tree.open(self.main_key, f"{self.group_path}\\{code_int}", file=self.file).items()
                if data_dict['parent']:
                    demo(data_dict['parent'])
                    ret_list.append(data_dict['parent'])

            try:
                demo(d_dict['parent'])
                ret_list.append(d_dict['parent'])
                return '', ret_list
            except DBError:
                return '此code无效'
        else:
            return []


class SRoomIOTMiddle(SRoomDB, IOTBaseDB):
    """
    机房和动环中间表基本方法
    """
    group_by_key = "type"
    data_sort_key = "priority"
    query_field = ["mxlabel", "mxdevicetype", "mxparent", "isdel", "_target_ip", "_port", "_Addr"]

    def get_sub_monitor(self, code, device_data) -> NoReturn:
        """
        或者一个子级信息基本方法
        @param device_data:
        @param code:
        @return:
        """
        monitor_res_dict = {}
        try:
            ups_sub_list = self.tree.open("MXSE", "1\\1.SD\\%s\\%s.SubMonitor" % (code, code),
                                          file="ccubase").sub_keys()
            for ups_sub_key in ups_sub_list:
                ups_sub_monitor = self.tree.open("MXSE",
                                                 "1\\1.SD\\%s\\%s.SubMonitor\\%s" % (code, code, ups_sub_key),
                                                 file="ccubase").items(prop_list="mxpluginname")

                monitor_res_dict[ups_sub_key] = ups_sub_monitor["mxpluginname"]
        except DBError as e:
            logging.error(e)

        device_data["sub_monitor"] = monitor_res_dict


class RoomOverviewDB(SRoomIOTMiddle, IOTBaseServer):
    over_path = 'cabine_manage'
    group_by_key = "device_type"

    def __init__(self):
        super().__init__()
        self.middle_data = {}
        self.code = ""
        self.is_double = True

    def retrieve(self, code):
        """
        查询设备 重写的原因 是在概览的情况下 会调用 SRoomDB 的 retrieve 方法
        @param code:
        @return:
        """
        try:

            device_data = self.tree.open("MXSE", "1\\1.SD\\%s" % code, file="ccubase").items(self.query_field)

            device_data["code"] = code
            if device_data.get("isdel", 1):
                raise VerifyError(_("查询设备错误 is_del"))
            self.get_sub_monitor(code, device_data)
        except DBError as e:
            logging.error(e)
            raise VerifyError(_("查询设备错误"))
        return device_data

    def cabinet(self, code):
        """
        查找机柜信息
        @param code:
        @return:
        """
        try:
            ca_len, ca_key_list = self.tree.open(self.main_key, f'{self.over_path}', file=self.file).filter(
                parent=code)
        except DBError as e:
            logging.error(e)
            raise VerifyError(_("查询失败"))
        ret_dict = {'total_space': 0, }
        binding_sd = 0
        if ca_key_list:
            data_dict = self.tree.open(self.main_key, f'{self.over_path}', file=self.file).sub_items(
                key_list=ca_key_list, prop_list=['total_space', 'binding_sd'])
            for key, val in data_dict.items():
                ret_dict['total_space'] += val.get('total_space', 0)
                binding_sd += int(val.get('binding_sd_space', 0))
        ret_dict['available_space'] = ret_dict['total_space'] - binding_sd

        return ret_dict

    def overview(self, data_obj):

        self.middle_data = self.group_by(self.query_middle_all(data_obj))
        res_dict = {"state": True}
        self.code = data_obj.sroom_code
        #
        self.model_process(res_dict, self.get_overview())
        return res_dict
        # return self.middle_data

    def device_info(self, device_type, state: dict = None):
        """
        查找动环设备
        @return:
        """
        devic_type_dict = {"ModbusAC": ACSelectServer(),
                           "AirConditioning": PrecisionACSelectServer(),
                           "GasDetector": GASDeviceSelectServer(),
                           "Power": PowerDeviceSelectServer(),
                           "UpsDevice": UPSSelectServer(),
                           "Water": WaterCheckServer(),
                           "TemperatureHumidity": TemHumidityCheckServer(),
                           "janitor": RecordServer(),
                           "Video": None,
                           "cabinet": self
                           }
        # 关联的设备
        device_middle_type = self.middle_data.get(device_type)
        # 设备的模板
        device_type_obj = devic_type_dict.get(device_type)
        if device_middle_type and device_type_obj:
            # 动环设备
            if isinstance(device_type_obj, (IOTBaseServer, WaterCheckServer)):
                device_data = device_type_obj.device_info(device_middle_type, state)

                return {"count": self.statistics_count(device_data), "data": device_data}
            if isinstance(device_type_obj, RecordServer):
                # 获取机柜容量
                return device_type_obj.get_count(device_middle_type)

        if device_type_obj:
            if isinstance(device_type_obj, RoomOverviewDB):
                # 获取机柜容量
                return device_type_obj.cabinet(self.code)

        return ["啥也咩有"]

    def param_middle(self, data_obj) -> dict:
        """
        基础查询 参数
        @param data_obj:
        @return:
        """
        return {"sroom_code": data_obj.sroom_code}

    def model_process(self, res_dict: dict, get_overview: dict):
        """
        递归模板处理
        @param get_overview:
        @param res_dict:
        @return:
        """
        for model_key, model_data in get_overview.items():

            if model_data.get("type") is not None:
                device_info = self.device_info(model_data["type"], res_dict)
                if self.is_double:
                    res_dict[model_data["property"]] = device_info
            else:
                sub_res = res_dict[model_data["property"]] = {"state": 3}
                self.model_process(sub_res, model_data["sub"])
                if sub_res["state"] not in (3, 1):
                    res_dict["state"] = False


class GroupOverviewDB(RoomOverviewDB):
    over_path = 'cabine_manage'
    group_by_key = "device_type"

    def __init__(self):
        super().__init__()
        self.middle_data = {}
        self.code = ""
        self.is_double = False


class IOTRelevanceDB(SRoomIOTMiddle):
    """
    LIUYANWEI
    机房关联动环设备
    """

    def create(self, data_obj):
        """
        创建总结表
        @param data_obj:
        @return:
        """
        mid_key = self.query_middle(data_obj=data_obj)
        if mid_key is None:
            self.tree.open(self.main_key, "sroom_iot_middle", file=self.file).insert_key_items(data_obj)
        return True

    def query_middle(self, data_obj):
        """
        查询结果查找一个
        @param data_obj:
        @return:
        """
        total, mid_key = self.tree.open(self.main_key, "sroom_iot_middle", file=self.file).filter(
            device_type=data_obj.device_type,
            iot_code=data_obj.iot_code,
            sroom_code=data_obj.sroom_code)
        if mid_key:
            mid_value = self.tree.open(self.main_key, "sroom_iot_middle\\%s" % mid_key[0], file=self.file).items()
            mid_value["code"] = mid_key
            return mid_value
        else:
            return None


class IOTOperationDB(SRoomIOTMiddle):

    def update(self, code, **kwargs):
        """
        更新
        @param code:
        @param kwargs:
        @return:
        """
        try:
            self.tree.open(self.main_key, "sroom_iot_middle\\%s" % code, file=self.file).insert_item("priority",
                                                                                                     kwargs["priority"])
            logging.info("%s\\sroom_iot_middle\\%s priority 属性 值设置为 %s" % (self.main_key, code, kwargs["priority"]))
        except DBError as e:
            logging.error(e)
            raise ParamsError(_("更新失败"))

    def delete(self, code, **kwargs):
        """
        删除
        @param code:
        @return:
        """
        try:
            self.tree.open(self.main_key, "sroom_iot_middle\\%s" % code, file=self.file).delete()
            logging.info("%s\\sroom_iot_middle\\%s priority key以删除" % (self.main_key, code))
        except DBError as e:
            logging.error(e)
            raise ParamsError(_("删除失败"))
